package com.shop.loan.handler;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.shop.loan.mapper.LoanOrderByMybatisMapper;
import com.shop.loan.mapper.UserBankByMybatisMapper;
import com.shop.loan.model.common.Code;
import com.shop.loan.model.common.Constant;
import com.shop.loan.model.common.ResResult;
import com.shop.loan.model.entity.LoanOrderByMybatis;
import com.shop.loan.model.entity.UserBankByMybatis;
import com.shop.loan.model.vo.PayVo;
import com.shop.loan.model.vo.WithholdVo;
import com.shop.loan.redis.RedisCache;
import com.shop.loan.redis.RedisLockUtil;
import com.shop.loan.redis.RedisUtil;
import com.shop.loan.service.PayService;
import com.shop.loan.util.Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import xyz.erupt.annotation.fun.OperationHandler;
import xyz.erupt.upms.service.EruptUserService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.UUID;

@Slf4j
@Service
public class WithholdHandler implements OperationHandler<Object, WithholdVo> {

    @Resource
    RedisLockUtil redisLockUtil;

    @Resource
    RedisUtil redisUtil;

    @Resource
    EruptUserService eruptUserService;

    @Resource
    LoanOrderByMybatisMapper loanOrderByMybatisMapper;

    @Resource
    UserBankByMybatisMapper userBankByMybatisMapper;

    @Resource
    PayService payService;

    @Resource
    HttpServletRequest httpServletRequest;

    @Override
    public String exec(List<Object> data, WithholdVo withholdVo, String[] param) {
        JSONObject paramJs = (JSONObject) httpServletRequest.getAttribute(Constant.ATTRIBUTES_PARAM_KEY);
        JSONArray ids = paramJs.getJSONArray("ids");
        if (ids == null || ids.size() == 0) {
            return "msg.error('未选中数据!')";
        }
        if (withholdVo.getMoney().doubleValue() <= 0) {
            return "msg.error('代扣金额异常')";
        }
        Jedis jedis = redisUtil.getJedis();
        String lockKey = RedisCache.withholdAdminLock;
        String lockValue = UUID.randomUUID().toString();
        String info = "";
        try {
            if (!redisLockUtil.lock(jedis, lockKey, lockValue)) {
                return "msg.error('请稍后再操作')";
            }
            for (Object item : ids) {
                Long id = Long.parseLong(item.toString());
                LoanOrderByMybatis loanOrderByMybatis = loanOrderByMybatisMapper.selectByPrimaryKey(id);

//                List<UserBankByMybatis> userBankByMybatisList = userBankByMybatisMapper.selectByUser(loanOrderByMybatis.getUserId());
//                if (userBankByMybatisList == null || userBankByMybatisList.size() <= 0) {
//                    info = info + ",【" + id + "-该客户未绑卡】";
//                    continue;
//                }

                UserBankByMybatis userBankByMybatis = userBankByMybatisMapper.selectByPrimaryKey(loanOrderByMybatis.getBankId());
                if (userBankByMybatis == null || userBankByMybatis.getIsDelete()) {
                    log.error("用户订单银行卡为空：{}", loanOrderByMybatis.getUserId());
                    continue;
                }

                PayVo payVo = new PayVo();
                payVo.setOpIp(loanOrderByMybatis.getOrderIp());
                payVo.setOrderId(loanOrderByMybatis.getId());
                payVo.setPayType(withholdVo.getPayType());
                payVo.setOpId(loanOrderByMybatis.getUserId());
                payVo.setPFrom(loanOrderByMybatis.getPFrom());
                payVo.setBindCardId(userBankByMybatis.getProtocol());
                payVo.setAmount(withholdVo.getMoney());
                payVo.setRemark(eruptUserService.getCurrentUid() + "-代扣");
                ResResult payRes = payService.readyPay(payVo, true);
                if (payRes.getCode().intValue() == Code.SUCCESS.getCode().intValue()) {
                    info = info + ",【" + id + "-已提交】";
                } else {
                    info = info + ",【" + id + "-" + payRes.getMsg() + "】";
                }
                Thread.sleep(100);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(Util.GetErrorDetails(e));
        } finally {
            if (jedis != null) {
                redisLockUtil.release(jedis, lockKey, lockValue);
                jedis.close();
            }
        }
        return "alert('" + info + "')";
    }


//    @Override
//    public WithholdVo eruptFormValue(List<Object> data, WithholdVo withholdVo, String[] param) {
//        Object item = data.get(0);
//        JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(item));
//        Long id = jsonObject.getLongValue("id");
//
//        LoanOrderByMybatis loanOrderByMybatis = loanOrderByMybatisMapper.selectByPrimaryKey(id);
//        LoanOrderBillByMybatis loanOrderBillByMybatis = loanOrderBillByMybatisMapper.selectFirstUnPay(id);
//
//        if (loanOrderByMybatis == null || loanOrderBillByMybatis == null) {
//            return withholdVo;
//        }
//
//        BigDecimal periodPayMoney = loanOrderPayLogByMybatisMapper.selectSumByBillId(loanOrderBillByMybatis.getId(), null, PayType.principal_interest.getType());
//        periodPayMoney = periodPayMoney == null ? BigDecimal.ZERO : periodPayMoney;
//        BigDecimal periodGuaranteePayMoney = loanOrderPayLogByMybatisMapper.selectSumByBillId(loanOrderBillByMybatis.getId(), null, PayType.goods.getType());
//        periodGuaranteePayMoney = periodGuaranteePayMoney == null ? BigDecimal.ZERO : periodGuaranteePayMoney;
//
//        withholdVo.setTotalMoney(loanOrderByMybatis.getMoney().add(loanOrderByMybatis.getRateMoney()).add(loanOrderByMybatis.getShopMoney()));
//        withholdVo.setPayMoney(loanOrderByMybatis.getPayMoney());
//        withholdVo.setPeriod(loanOrderBillByMybatis.getPeriod());
//        withholdVo.setTotalPeriod(loanOrderBillByMybatis.getTotalPeriod());
//        withholdVo.setPeriodMoney(loanOrderBillByMybatis.getMoney());
//        withholdVo.setPeriodRateMoney(loanOrderBillByMybatis.getRateMoney());
//        withholdVo.setPeriodPayMoney(periodPayMoney);
//        withholdVo.setPeriodDiscountMoney(loanOrderBillByMybatis.getDiscountsMoney() == null ? BigDecimal.ZERO : loanOrderBillByMybatis.getDiscountsMoney());
//        withholdVo.setPeriodDiscountMoneyByGuarantee(loanOrderBillByMybatis.getDiscountsMoneyByGoods() == null ? BigDecimal.ZERO : loanOrderBillByMybatis.getDiscountsMoneyByGoods());
//        loanOrderBillByMybatis.setPayMoney(periodPayMoney);
//        withholdVo.setPeriodUnMoney(Util.getUnPayMoneyByPi(loanOrderBillByMybatis));
//        withholdVo.setPeriodGuaranteeMoney(loanOrderBillByMybatis.getShopMoney());
//        withholdVo.setPeriodGuaranteePayMoney(periodGuaranteePayMoney);
//        withholdVo.setPeriodGuaranteeUnMoney(Util.getUnPayMoneyByGuarantee(loanOrderBillByMybatis.getShopMoney(), loanOrderBillByMybatis.getDiscountsMoneyByGoods(), periodGuaranteePayMoney));
//        return withholdVo;
//    }


}
